<template>
  <div class="login-container">
    <el-card class="login-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h1 class="title">剧本杀管理系统</h1>
          <p class="subtitle">欢迎回来</p>
        </div>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="rules"
        @submit.prevent="handleLogin"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.account"
            placeholder="请输入用户名或邮箱"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleLogin"
            :loading="loading"
            class="login-btn"
            size="large"
          >
            {{ loading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer">
        <el-text type="info" size="small">
          还没有账户？
          <router-link to="/register" class="register-link">立即注册</router-link>
        </el-text>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { type FormInstance, type FormRules } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { loginAPI } from '@/api/user'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user'
const router = useRouter()

const loginFormRef = ref<FormInstance>()
const loading = ref(false)

const loginForm = reactive({
  account: '',
  password: '',
})

const rules = reactive<FormRules>({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
  ],
})

const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate((valid) => {
    if (valid) {
      submitLogin()
    }
  })
}

const submitLogin = async () => {
  loading.value = true

  try {
    const { data: res } = await loginAPI(loginForm)
    console.log(res)
    if (res.code !== 1) {
      ElMessage.error(res.msg || '登录失败！')
      return
    }
    // 保存到store（插件会自动持久化）
    const userStore = useUserStore()
    userStore.setToken(res.data.token)
    userStore.setUserInfo(res.data.userInfo)
    userStore.setMenuList(res.data.menuList)
    console.log('userStore',userStore);

    ElMessage.success(res.msg || '登录成功！')

    // 直接跳转到首页，让路由守卫处理动态路由的添加
    // 使用replace而不是push，避免在历史记录中留下登录页
    router.replace('/')
  } catch (error) {
    ElMessage.error(error.msg || '登录失败，请检查用户名和密码')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  padding: 1rem;
}

.login-card {
  width: 100%;
  max-width: 400px;
}

.card-header {
  text-align: center;
}

.title {
  font-size: 1.5rem;
  font-weight: 500;
  color: #333;
  margin: 0 0 0.5rem 0;
}

.subtitle {
  font-size: 0.875rem;
  color: #666;
  margin: 0;
}

.login-btn {
  width: 100%;
}

.footer {
  text-align: center;
  margin-top: 1rem;
}

.register-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 0.25rem;
}

.register-link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .login-container {
    padding: 0.75rem;
  }

  .login-card {
    max-width: 100%;
  }

  .title {
    font-size: 1.25rem;
  }
}

@media (max-width: 480px) {
  .login-container {
    padding: 0.5rem;
  }

  .title {
    font-size: 1.125rem;
  }
}
</style>
